package com.cfuture08.eweb4j.mvc;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cfuture08.eweb4j.component.dwz.DWZUtil;
import com.cfuture08.eweb4j.mvc.config.bean.MVCConfigBean;
import com.cfuture08.eweb4j.mvc.config.bean.Validator;

public class DoValidate {
	public static Map<String, String> checkValidate(MVCConfigBean mvcBean,
			Map<String, String[]> map, HttpServletRequest request)
			throws Exception {
		Map<String, String> error = null;
		// 启动验证器
		for (Validator val : mvcBean.getValidator()) {
			ValidatorIF validator = null;
			if (!"".equals(val.getName())) {
				// 根据name属性实例化相关的验证器，如果找不到，就根据class属性实例化
				validator = ValidatorFactory.getValidator(val.getName());
				if (validator == null) {
					validator = (ValidatorIF) Class.forName(val.getClazz())
							.newInstance();
				}
			}

			if (validator != null) {
				// 执行验证
				error = validator.validate(val, map, request);
				if (error != null) {
					break;
				}
			}
		}

		return error;
	}

	public static void doValidate(MVCConfigBean mvcBean,
			Map<String, String> error, HttpServletRequest req,
			HttpServletResponse res, PrintWriter out) throws Exception {

		if (ValidatorConstant.DEFAULT_LOC.equals(mvcBean.getShowErrorType())
				|| ValidatorConstant.ALERT_LOC.equals(mvcBean
						.getShowErrorType())) {
			StringBuilder emss = new StringBuilder();
			for (String s : error.keySet()) {
				emss.append(error.get(s)).append(";");
			}
			out.print("<script>alert('" + emss.toString()
					+ "');javascript:history.go(-1)</script><center></center>");
		} else if (ValidatorConstant.AJAX_OUT_LOC.equals(mvcBean
				.getShowErrorType())) {
			StringBuilder emss = new StringBuilder();
			for (String s : error.keySet()) {
				emss.append(error.get(s));
			}

			out.print(emss.toString());
		} else if (ValidatorConstant.DWZ_JSON_LOC.equals(mvcBean
				.getShowErrorType())) {
			StringBuilder emss = new StringBuilder();
			for (String s : error.keySet()) {
				emss.append(error.get(s));
			}

			out.print(DWZUtil.getFailedJson(emss.toString()));
		} else {
			// 如果是填写跳转页面的话
			req.setAttribute("valError", error);
			req.getRequestDispatcher(mvcBean.getShowErrorType()).forward(req,
					res);
		}

		return;
	}
}
